import { define, min, obj, req, str } from '@knno/valid';
import { DefaultContext, body, HttpError, title, desc, result } from '@knno/web';

const def = define(() =>
	req(
		obj({
			account: req(str(min(1))), // 账号
			password: req(str(min(1))), // 密码
		})
	)
);

@title('登录')
export default class {
	@body(def)
	@desc('调用登录接口：检查账号和密码是否合法，成功后把账号写入 Session，表示登录成功。')
	@result('无返回值，仅仅设置 session 信息，如果失败会返回 Http 401 错误。')
	async post(ctx: DefaultContext): Promise<void> {
		const query = await ctx.body.json(def);
		// should verify account and password by database or ldap etc..
		if (query.account === 'admin' && query.password === 'admin') {
			ctx.session.set('account', query.account);
		} else {
			throw new HttpError(401, 'Invalid account or password');
		}
	}
}
